import { defineStore } from 'pinia'
import { login, logout } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
// import type { LoginFormType, LoginResponseType, ResponseType } from '@/types/user'

export default defineStore('user', {
  state() {
    return {
      avatarURL: 'https://q.qlogo.cn/headimg_dl?dst_uin=1207588603&spec=100',
      token: getToken(),
      roles: [],
    }
  },

  actions: {
    // 用户登录
    async login(userInfo: UserType.LoginForm) {
      try {
        const { username, password } = userInfo
        const loginResult = await login({ username: username.trim(), password: password })
        const { token } = loginResult.data
        this.token = token
        setToken(token)
      } catch (error) {
        return Promise.reject(error)
      }
    },

    // 退出登录
    async logout() {
      try {
        this.token = ''
        this.roles = []
        removeToken()
        await logout()
        // resetRouter()
      } catch (error) {
        return Promise.reject(error)
      }
    },

    // 重置用户 token
    resetToken() {
      this.token = ''
      this.roles = []
      removeToken() // 清除 Cookie 的 token
    },
  },

  getters: {},
})
